<template>
  <div>
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="sel">
        <el-form-item>
          <el-input
            v-model="sel.realName"
            placeholder="用户名"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="sel.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始注册日期"
            end-placeholder="结束注册日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="userLocal"
            ><i class="el-icon-search"></i
          ></el-button>
          <el-button type="success" @click="dialog.addshow = true"
            >新建</el-button
          >
          <el-button type="success" @click="exportExcel">导出数据</el-button>
          <el-upload
              class="clearfix"
              action="http://localhost:9000/users/importExcel"
              name="file"
              :on-progress="onExcelProgress"
              :on-success="handleExcelSuccess"
              accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              multiple
              :limit="1"
              :headers="upload.headerObj"
            >
              <el-button type="primary">数据导入</el-button>
            </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="userList" stripe style="width: 100%">
      <el-table-column prop="tel" label="账号" width="180"> </el-table-column>
      <el-table-column prop="realName" label="姓名" width="160">
      </el-table-column>
      <el-table-column prop="birthday" label="生日"> </el-table-column>
      <el-table-column label="头像" show-overflow-tooltip>
        <template slot-scope="scope">
          <img
            :src="scope.row.headImg"
            alt=""
            style="width: 60px; height: 60px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="部门"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row.id)"
            >编辑</el-button
          >
          <el-popconfirm
            title="这是一段内容确定删除吗？"
            @confirm="handleDelete(scope.row.id)"
          >
            <el-button slot="reference" size="mini" type="danger"
              >删除</el-button
            >
          </el-popconfirm>
          <el-button
            type="success"
            size="mini"
            @click="assignRole(scope.row.id)"
            >分配</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="sel.currentPage"
      :page-sizes="page.pageSize"
      :page-size="sel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
    >
    </el-pagination>

    <el-dialog title="添加员工" :visible.sync="dialog.addshow" width="32%">
      <el-form ref="addForm" :model="addForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="电话/账号" prop="tel">
              <el-input v-model="addForm.tel"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="addForm.realName"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="headImg" hidden>
              <el-input v-model="addForm.headImg" clearable></el-input>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="addForm.birthday"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="addForm.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :label="item.deptName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.addshow = false">取 消</el-button>
        <el-button type="primary" @click="save()">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改员工" :visible.sync="dialog.updateshow" width="32%">
      <el-form ref="updateForm" :model="updateForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="电话/账号" prop="tel">
              <el-input v-model="updateForm.tel"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="updateForm.realName"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="updateForm.password"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="headImg" hidden>
              <el-input v-model="updateForm.headImg" clearable></el-input>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="updateForm.birthday"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="updateForm.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :label="item.deptName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.updateshow = false">取 消</el-button>
        <el-button type="primary" @click="update()">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="用户授权"
      :visible.sync="dialog.assingRolesVisible"
      width="30%"
    >
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          :label="item.id"
          v-for="(item, index) in roleList"
          :key="index"
          >{{ item.roleName }}</el-checkbox
        >
      </el-checkbox-group>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.assingRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      upload: {
        headerObj: {
          //Spring security时需要传递token，否则不需要该配置
          Authorization: sessionStorage.getItem("authorization"),
        },
      },
      uid: 0,
      checkList: [], //选中的角色
      roleList: [], //所有角色
      addForm: {},
      updateForm: {},
      deptList: {},
      dialog: {
        addshow: false,
        updateshow: false,
        assingRolesVisible: false,
      },
      userList: [],
      page: {
        // 下拉框的数据
        pageSize: [5, 10, 30, 50, 100],
        //总数
        total: 0,
      },
      sel: {
        //当前第几页
        currentPage: 1,
        //一页多少行
        pageSize: 5,
        realName: "",
        dateRange: [],
      },
    };
  },
  methods: {
    //文件上传成功的钩子函数
    handleExcelSuccess(res, result) {
      this.$message.success("导入成功");
      if (result.response.success) {
        this.userLocal();
      }
    },
    // 上传中
    onExcelProgress() {},
    exportExcel() {
      this.$axios
        .post("users/exportExcel", this.sel, { responseType: "blob" })
        .then((res) => {
          let fileName = res.headers["content-disposition"].split("=")[1]; //得到后端生成的文件名
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let dom = document.createElement("a");
          dom.style.display = "none";
          dom.href = url;
          dom.setAttribute("download", fileName); //指定下载后的文件名，防跳转
          document.body.appendChild(dom);
          dom.click();
          // 释放内存
          dom.parentNode.removeChild(dom);
          window.URL.revokeObjectURL(dom.href);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    updateRole() {
      this.$axios
        .post("roles", {
          uid: this.uid,
          rids: this.checkList,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("授权成功");
            this.dialog.assingRolesVisible = false;
            this.checkList = [];
            this.uid = 0;
          }
        });
    },
    assignRole(id) {
      this.dialog.assingRolesVisible = true;
      this.$axios.get("/roles/" + id).then((res) => {
        this.uid = id;
        this.roleList = res.data.data.roleList;
        this.checkList = res.data.data.checkList;
      });
    },

    handleDelete(id) {
      this.$axios.delete("/users/del/" + id).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("删除成功~");
          this.userLocal();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    update() {
      this.$axios.put("/users", this.updateForm).then((res) => {
        if ((res.data.code = 200)) {
          this.dialog.updateshow = false;
          this.$message.success("修改成功~");
          this.userLocal();
        }
      });
    },
    handleEdit(id) {
      this.dialog.updateshow = true;
      this.$axios
        .get("/users/" + id)
        .then((res) => {
          this.updateForm = res.data.data.list;
        })
        .catch((error) => {
          this.$message.error("出错了，稍后重试");
        });
    },
    // 每页数据改变时
    handleSizeChange(size) {
      this.sel.pageSize = size;
      this.userLocal();
    },
    //改变页码时
    handleCurrentChange(val) {
      this.sel.currentPage = val;
      this.userLocal();
    },
    userLocal() {
      this.$axios.post("/users/selAll", this.sel).then((res) => {
        this.userList = res.data.data.userList;
        this.page.total = res.data.data.total;
        (this.sel.realName = ""), (this.sel.dateRange = []);
      });
    },
    loadDept() {
      this.$axios
        .get("/depts")
        .then((res) => {
          this.deptList = res.data.data.list;
        })
        .catch((error) => {
          this.$message.error("出错了，稍后重试");
        });
    },
    save() {
      this.$axios.post("/users", this.addForm).then((res) => {
        if ((res.data.code = 200)) {
          this.dialog.addshow = false;
          this.$message.success("添加成功~");
          this.addForm = [];
          this.userLocal();
        }
      });
    },
  },
  mounted() {
    this.userLocal();
    this.loadDept();
  },
};
</script>
